//
//  CategoryManagerView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 27.03.25.
//

import SwiftUI

struct CategoryManagerView: View {
    
    @Environment(\.presentToast) var presentToast
    @Environment(\.presentationMode) var presentationMode
    
    @State var sheet = false
    @State var alert = false
    @State var currentDetent = PresentationDetent.large
    @StateObject var viewModel = CategoryManagerViewModel()
    @State var categoryType: CategoryType = .expense
    @State var selectedCategory: AccountingCategory? = nil
    @State var selectedParentCategory: AccountingCategory? = nil
    @State var navigateToCategoryAdd = false
    @State var navigateToCategoryUpdate = false
    @State var navigateToCategoryAddSub = false
    @State var navigateToCategorySort = false
    @State var navigateToCategorySelect = false
    @State var navigateToCategoryTransfer = false
    @State var showCategoryAlertMenu = false
    @State var showCategoryDeleteAlertMenu = false
    @State var actionMenu = ActionSheetMenuType.categoryOperation
    
    var body: some View {
        ZStack {
            Color.white.ignoresSafeArea()
            VStack {
                ZStack {
                    HStack {
                        Button(action: {
                            presentationMode.wrappedValue.dismiss()
                        }) {
                            Image(systemName: "chevron.backward")
                                .renderingMode(.template)
                                .foregroundColor(Color.koiColorTitle)
                                .padding(.horizontal,16)
                        }
                        Spacer()
                    }
                    HStack {
                        Spacer()
                        CategoryTypeView(categoryType: $categoryType)
                        Spacer()
                    }
                    HStack {
                        Spacer()
                        Button(action: {
                            navigateToCategoryAdd.toggle()
                        }) {
                            Text("新增类别")
                                .font(.system(size: 14))
                                .bold()
                                .foregroundColor(Color.koiColorPrimary)
                                .padding(.horizontal,16)
                        }
                    }
                }.padding(EdgeInsets(top: 16, leading: 0, bottom: 6, trailing: 0))
                TabView(selection: $categoryType) {
                    CategoryManagerListView(
                        categoryListData: $viewModel.expenseList,
                        subCategoryListData: $viewModel.subCategoryListData,
                        loadSubCategory: { parent in
                            selectedParentCategory = parent
                            viewModel.loadSubCategorys(parent: parent)
                        },
                        selectedCategoryClick: { clickItem in
                            selectedCategory = clickItem
                            showCategoryAlertMenu = true
                            actionMenu = .categoryOperation
                        },
                        addCategoryClick: { clickItem in
                            selectedCategory = clickItem
                            navigateToCategoryAddSub = true
                        }
                    ).tag(CategoryType.expense)
                    CategoryManagerListView(
                        categoryListData: $viewModel.incomeList,
                        subCategoryListData: $viewModel.subCategoryListData,
                        loadSubCategory: { parent in
                            selectedParentCategory = parent
                            viewModel.loadSubCategorys(parent: parent)
                        },
                        selectedCategoryClick: { clickItem in
                            selectedCategory = clickItem
                            showCategoryAlertMenu = true
                            actionMenu = .categoryOperation
                        },
                        addCategoryClick: { clickItem in
                            selectedCategory = clickItem
                            navigateToCategoryAddSub = true
                        }
                    ).tag(CategoryType.income)
                }.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            }
        }
        .background(Color.koiColorBackground)
        .navigationDestination(
            isPresented: $navigateToCategoryAdd,
            destination: { CategoryAddView(selectedCategoryType:categoryType) }
        )
        .navigationDestination(
            isPresented: $navigateToCategoryUpdate,
            destination: {
                if (selectedCategory != nil) {
                    CategoryAddView.updateCategory(category: selectedCategory!)
                } else {
                    EmptyView()
                }
            }
        )
        .navigationDestination(
            isPresented: $navigateToCategoryAddSub,
            destination: {
                if (selectedCategory != nil) {
                    CategoryAddView.createSub(parent: selectedCategory!)
                } else {
                    EmptyView()
                }
            }
        )
        .navigationDestination(isPresented: $navigateToCategorySort, destination: {
            if (selectedCategory != nil) {
                CategorySortView(selectedCategory: selectedCategory!)
            } else {
                EmptyView()
            }
        })
        .navigationBarBackButtonHidden()
        .onChange(of: viewModel.deleteState) { newValue in
            if (newValue == "success") {
                // 删除成功
                // 还要重置一下，否则下一次不会通知改变
                viewModel.deleteState = ""
                presentToast(.init(message: "类别删除成功"))
                viewModel.loadCategorys()
                if let parent = selectedParentCategory {
                    viewModel.loadSubCategorys(parent: parent)
                }
            }
        }
        .onChange(of: viewModel.changeState) { newValue in
            if (newValue == "success") {
                viewModel.changeState = ""
                presentToast(.init(message: "修改成功"))
                viewModel.loadCategorys()
                if let parent = selectedParentCategory {
                    viewModel.loadSubCategorys(parent: parent)
                }
            }
        }
        .onChange(of: viewModel.transferState) { newValue in
            if (newValue == "success") {
                viewModel.transferState = ""
                presentToast(.init(message: "记账数据转移成功"))
                viewModel.loadCategorys()
                if let parent = selectedParentCategory {
                    viewModel.loadSubCategorys(parent: parent)
                }
            }
        }
        .onAppear {
            viewModel.loadCategorys()
//            if (selectedParentCategory != nil) {
//                viewModel.loadSubCategorys(parent: selectedParentCategory!)
//            }
        }
        .sheet(isPresented:$navigateToCategorySelect) {
            if (selectedCategory != nil) {
                CategorySelectListView(title: "选择一级类别", selectedCategory: selectedCategory!) { itemCategory in
                    // 更新类别为二级类别
                    viewModel.changeToSubCategory(selectedCategory: selectedCategory, parentCategory: itemCategory)
                }.presentationDetents([.medium])
            } else {
                EmptyView()
            }
            
        }
        .sheet(isPresented: $navigateToCategoryTransfer) {
            if let selectedCategory = selectedCategory {
                CategorySelectListView(title: "选择转入类别", selectedCategory: selectedCategory, categoryItemClick: { itemCategory in
                    // 转移数据
                    viewModel.transferCategory(oldCid: selectedCategory.cid, newCid: itemCategory.cid)
                }).presentationDetents([.medium])
            } else {
                EmptyView()
            }
        }
        .actionSheet(isPresented: $showCategoryAlertMenu) {
            switch actionMenu {
            case .categoryOperation:
                var buttons = Array<ActionSheet.Button>()
                buttons.append(.default(Text("编辑类别")) {
                    if (selectedCategory != nil) {
                        navigateToCategoryUpdate.toggle()
                    }
                })
                if (selectedCategory?.parentId == nil) {
                    buttons.append(.default(Text("改为二级类别")) {
                        // 如果所选类别有子类别不能改为二级类别
                        if (selectedCategory?.hasSubCategory == true) {
                            presentToast(.init(message: "该类别下已包含二级类别，无法更改"))
                        } else {
                            navigateToCategorySelect = true
                        }
                    })
                } else {
                    buttons.append(.default(Text("改为一级类别")) {
                        // 二级类别改为一级类别
                        viewModel.changeToFirstCategory(selectedCategory: selectedCategory)
                    })
                }
                buttons.append(.default(Text("排序")) {
                    navigateToCategorySort = true
                })
                buttons.append(.default(Text("删除类别")) {
                    // 有二级类别提示先删除二级类别
                    guard let category = selectedCategory else {
                        return
                    }
                    if (category.hasSubCategory) {
                        presentToast(.init(message: "该类别下包含二级类别，无法删除，请先删除二级类别"))
                        return
                    }
                    // 显示删除确认弹窗
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        showCategoryAlertMenu = true
                        actionMenu = .categoryDeleteConfirm
                    }
                })
                buttons.append(.cancel(Text("取消")))
                return ActionSheet(title: Text(""),buttons:buttons)
            case .categoryDeleteConfirm:
                // 如果类别下有数据，显示转移数据
                var sheetTitle = "删除类别操作同时会删除该类别下所有记账数据"
                var buttons = Array<ActionSheet.Button>()
                if (selectedCategory?.hasRecord == true) {
                    buttons.append(.default(Text("转移记账数据")) {
                        self.navigateToCategoryTransfer = true
                    })
                    sheetTitle = "删除类别操作同时会删除该类别下所有记账数据，您也可以把记账数据转移到其他类别"
                }
                buttons.append(.destructive(Text("确认删除")) {
                    // 删除类别数据
                    viewModel.deleteCategory(selectedCategory:selectedCategory)
                })
                buttons.append(.cancel(Text("取消")))
                return ActionSheet(title: Text(sheetTitle),buttons: buttons)
            }
        }
    }
}

enum ActionSheetMenuType {
    case categoryOperation , categoryDeleteConfirm
}

#Preview {
    CategoryManagerView()
}
